package com.cms.recursoshumanos.activity.directorio;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.cms.recursoshumanos.cache.ListaContactosCache;
import com.cms.recursoshumanos.component.adapter.SeparatedListAdapter;
import com.cms.recursoshumanos.constant.Constant;
import com.cms.recursoshumanos.object.Contacto;
import com.cms.recursoshumanos.object.ObjectContactoElemento;
import com.cms.recursoshumanos.object.list.ListaContacto;
import com.cms.recursoshumanos.object.list.ListaContactosDirectorio;
import com.example.frontendrecursoshumanos.R;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class DirectorioMainActivity extends FragmentActivity implements
		ActionBar.TabListener {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_directorio_main);
		
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.directorio_main, menu);
		return true;
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public static void hideSoftKeyboard(Activity activity) 
	{
	    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
	    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
	}
	
	
	@SuppressLint("ValidFragment")
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) 
		{
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			Fragment fragment;
			fragment = new DummySectionFragment();
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) 
		{
			Locale l = Locale.getDefault();
			switch (position) 
			{
			case 0:
				return "Directorio".toUpperCase(l);
			case 1:
				return "Favoritos".toUpperCase(l);
			
			}
			return null;
		}
	}

	
	
	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	
	public static class DummySectionFragment extends Fragment 
	{
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";
		
		private ListaContactosDirectorio listado_contacto;
		private EditText buscador;
		private ListView listaContactoView;
		private LinearLayout layout_lista_letra;
		private LinearLayout layout_lista_contacto;
		private LinearLayout layout_cantidad_contacto;
		private TextView textCantidadContacto;
		private int posicion;
		
		public DummySectionFragment() 
		{
			this.listado_contacto = ListaContactosCache.getInstance().getListaContactoDirectorio();
			
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) 
		{
			View rootView = inflater.inflate(
					R.layout.fragment_directorio_main_dummy, container, false);
			posicion = getArguments().getInt(ARG_SECTION_NUMBER);
			
			layout_lista_contacto = (LinearLayout) rootView.findViewById(R.id.llListaContacto);
			listaContactoView = (ListView) layout_lista_contacto.findViewById(R.id.lvContacto);
			layout_cantidad_contacto = (LinearLayout) layout_lista_contacto.findViewById(R.id.llCantidadConcatos);
			textCantidadContacto = (TextView) layout_cantidad_contacto.findViewById(R.id.tvCantidadContacto);
			buscador = (EditText) layout_lista_contacto.findViewById(R.id.etSearch);
			
			if (posicion == 0)
			{
				setConcatoComponents(rootView);
			}
			else if (posicion == 1)
			{
				setFavoritoComponents(rootView);
			}
			return rootView;
		}
		public void ListenerIndex(View arg0)
		{
			String firstLetter = (String) ((TextView) arg0).getText();
		    int index = 0;
		    if (layout_lista_letra != null) 
		    {
		        for (String string : Constant.TEXT_CONTACTO) 
		        {
		            if (string.startsWith(firstLetter))
		            {
		                index = layout_lista_letra.indexOfChild(arg0);
		                break;
		            }
		        }
		    }
			listaContactoView.setSelectionFromTop(index, 0);
		}
		public void setConcatoComponents(View rootView)
		{
			
			buscador.addTextChangedListener(new TextWatcher() 
			{

				   public void afterTextChanged(Editable s)
				   {
				   }

				   public void beforeTextChanged(CharSequence s, int start, int count, int after) 
				   {

				   }

				   public void onTextChanged(CharSequence s, int start, int before, int count) 
				   {
					   
					   int textlength = buscador.getText().length();
					   
					   if (textlength == 0)
					   {
						   setListadoConDivisiones(getActivity());
					   }
					   else
					   {
						   setListadoParamSinDivisiones(getActivity(), listado_contacto.getListaContactoSinDivisiones());
					   }

				   }
			});
			
			this.setListadoConDivisiones(rootView.getContext());
			
			
			

		}
		public void setListadoCompletoFavoritos(Context context, List<Contacto> listado_contacto_mostrar)
		{
			layout_cantidad_contacto.setVisibility(View.GONE);
			ListaContactoAdapter adaptador = new ListaContactoAdapter(context, listado_contacto_mostrar);
			listaContactoView.setAdapter(adaptador);
		}
		public void setListadoParamSinDivisiones(Context context, ListaContacto listado_contacto_fragment)
		{
			  
			int textlength = buscador.getText().length();
			
			List<Contacto> listado_contacto_mostrar = new ArrayList<Contacto>();
			   
			ListaContacto listado_contactos_sin_division = listado_contacto_fragment;
   
			for (int i = 0; i < listado_contactos_sin_division.cantElementListaContacto(); i++) 
			{
				Contacto contacto_aux = listado_contactos_sin_division.getContactoAtIndex(i);
	   
				String nombre_persona = contacto_aux.getEmpleado().getPersona().getApellido_Persona_1()+" "
			   					+contacto_aux.getEmpleado().getPersona().getNombre_Persona_1();
	   
				if (textlength <= nombre_persona.length()) 
				{
					if (buscador.getText().toString().equalsIgnoreCase(  (String) nombre_persona.subSequence(0,textlength))) 
					{
						listado_contacto_mostrar.add(contacto_aux);
					}
				}
			}
			
			layout_cantidad_contacto.setVisibility(View.VISIBLE);
			textCantidadContacto.setText("Se encontraron "+	listado_contacto_mostrar.size()+" registro(s).");
			ListaContactoAdapter adaptador = new ListaContactoAdapter(getActivity(), listado_contacto_mostrar);
			listaContactoView.setAdapter(adaptador);
			
		}
		public void setListadoConDivisiones(Context context)
		{
			layout_cantidad_contacto.setVisibility(View.GONE);
			SeparatedListAdapter adapter = new SeparatedListAdapter(context);
			
			ListaContactoAdapter adaptador;
			
			for (int i = 0; i < listado_contacto.cantElementListaObjectContactoElemento(); i++) 
			{
				ObjectContactoElemento listado_contacto_letra = listado_contacto.getListaObjectContactoElementoAtIndex(i);
				if (listado_contacto_letra.getListadoContacto().cantElementListaContacto() > 0)
				{
					adaptador = new ListaContactoAdapter(context, listado_contacto_letra.getListadoContacto().getListaContacto());
					adapter.addSection(listado_contacto_letra.getLetra(), adaptador);
				}
				
			}
			
			listaContactoView.setAdapter(adapter);
		}
		public void setFavoritoComponents(View rootView)
		{
			
			buscador.addTextChangedListener(new TextWatcher() 
			{

				   public void afterTextChanged(Editable s)
				   {
				   }

				   public void beforeTextChanged(CharSequence s, int start, int count, int after) 
				   {

				   }

				   public void onTextChanged(CharSequence s, int start, int before, int count) 
				   {
					   int textlength = buscador.getText().length();
					   if (textlength == 0)
					   {
						   setListadoCompletoFavoritos(getActivity(),listado_contacto.getListaFavorito().getListaContacto());
					   }
					   else
					   {
						   setListadoParamSinDivisiones(getActivity(), listado_contacto.getListaFavorito());
					   }
				   }
			});
			
			
			setListadoCompletoFavoritos(rootView.getContext(),listado_contacto.getListaFavorito().getListaContacto());
		
		}
		
		public void goDetailContacto(int persona_id, String letra_contacto)
		{
			Intent intent = new Intent(getActivity(), DetailContactoActivity.class);
			
			Bundle bundle = new Bundle();
			bundle.putInt("persona_id", persona_id);
			bundle.putString("letra_contacto", letra_contacto);
			intent.putExtras(bundle);
			
			startActivity(intent);
		}
		
		public class ListaContactoAdapter extends ArrayAdapter<Contacto>
		{
		    LayoutInflater mInflater ;  
		    private List<Contacto> mItems;
		    private ViewHolder holder;
		 
		    public ListaContactoAdapter  ( Context context , List<Contacto> items)  
		    {
		        super ( context, -1, items )  ;
		        this.mItems = items ;
		        this.mInflater = LayoutInflater.from(context) ;
		
		    }

		    @ Override
		    public View getView ( final int position_view, View convertView, ViewGroup parent )  
		    {
		            // Inflate the custom view
		    	
		    	if (convertView == null)
		    	{
		    		convertView =   mInflater.inflate( R.layout.elementos_lista_objeto_item,null);    		
		    		convertView.setOnClickListener(new OnClickListener() 
		    		{
						@Override
						public void onClick(View v) 
						{
							goDetailContacto(mItems.get(position_view).getEmpleado().getPersona().getPersonaId(),
									mItems.get(position_view).getEmpleado().getPersona().getApellido_Persona_1().substring(0,1));
						}
					});
		    		
		    		holder = new ViewHolder();
		    		holder.textViewNombreContacto = (TextView) convertView.findViewById(R.id.tvNombrePrincipal);
		    		holder.textViewDepartamentoContacto = (TextView) convertView.findViewById(R.id.tvNombreDetalle);
		    		
		    		convertView.setTag(holder);
		    	}
		    	else
		    	{
		    		holder = (ViewHolder)convertView.getTag();
		    	}
		    	
	    		holder.textViewNombreContacto.setText(mItems.get(position_view).getEmpleado().getPersona().getApellido_Persona_1()+", "+
	    								mItems.get(position_view).getEmpleado().getPersona().getNombre_Persona_1());
	    		holder.textViewDepartamentoContacto.setText(mItems.get(position_view).getEmpleado().getDepartamento().getNombre_Departamento());
	    		
		        return convertView ;
		    }
		    
		    private class ViewHolder 
		    {    	  
	        	  TextView  textViewNombreContacto;
	        	  TextView  textViewDepartamentoContacto;
	        }

		}
		
		
		
	}
	
	

}
